<?php

namespace App\Logic;

use Common\Model\PaymentModel;

class PaymentLogic extends PaymentModel {

    protected function _initialize() {
        parent::_initialize();
    }

    public function getPayData($query) {
        $field = array(
            'payment_type' => 'type',
            'payment_value' => 'value',
            'payment_loan_type' => 'loan_type',
            'payment_commodity_type' => 'commodity_type',
            'payment_stages' => 'stages',
        );

        $where = array(
            'payment_loan_type' => $query['loan_type'],
            'payment_commodity_type' => $query['commodity_type'],
            'payment_stages' => $query['stages'],
            'payment_status' => 1,
        );
        $data = $this->field($field)->where($where)->getItem();
        
        $data['payment'] = empty($data) ? false : true;

        return $data;
    }

    // 首付设置
    public function getDownPayment($query) {
        $field = array(
            'payment_type' => 'type',
            'payment_value' => 'value',
            'payment_data' => 'data',
        );
        
        $where = array(
            'payment_loan_type' => $query['loan_type'],
            'payment_commodity_type' => $query['commodity_type'],
            'payment_stages' => $query['stages'],
            'payment_status' => 1,
        );

        $data = $this->field($field)->where($where)->getItem();
        if ($data && !empty($data['data'])) {
            $data['data'] = json_decode($data['data'], true);
        }
        return $data;
    }

    public function getSecretKey() {
        return '72969e04baa8b6e43fae34e1969d56a6';
    }

    public function checkSign($data) {
        $clientSign = $data['sign'];
        $sign = $this->getSign($data);

        return $clientSign === $sign;
    }

    public function getSign($data) {
        unset($data['sign']);
        $sk = $this->getSecretKey();
        ksort($data);
        $query = '';
        foreach ($data as $key => $item) {
            $query .= "&{$key}={$item}";
        }
        
        $query = trim($query,'&');
        $query .= $sk;

        return md5($query);
    }

}
